import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import savePlugin from './sav-plugin'
import userModule from './modules/user'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 严格模式开发环境下启用严格模式，生产环境下启用生产模式
  strict: process.env.NODE_ENV !== 'production',
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || [],
  },
  getters: {
    // 是否全选
    allChecked(state) {
      return state.cart.every(prod => prod.checked)
    },
    // 计算选中商品的合计金额
    totalMoney(state) {
      return state.cart.reduce((sum, prod) => {
        if (prod.checked) {
          sum += prod.amount * prod.price * 100
        }
        return sum
      }, 0)
    },
    totalAmount(state) {
      return state.cart.reduce((sum, prod) => (sum += prod.amount), 0)
    },
  },
  mutations,
  actions: {},
  modules: {
    user: userModule,
  },
  plugins: [savePlugin],
})

export default store
